package servlet;


import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import dao.DaoFactory;
import dao.PhotoDao;
import dao.UserDao;

import entity.Photo;
import entity.User;

public class UserServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String uri=request.getRequestURI();
		String action=uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
		if("/register".equals(action)){
			HttpSession session = request.getSession();
			String validateCodeOfSession=(String) session.getAttribute("validateCode");
			String validateCode=request.getParameter("validateCode").toUpperCase();
			if(!validateCodeOfSession.equals(validateCode)){
				request.setAttribute("validateCodeErr", "验证码错误");
				request.getRequestDispatcher("register.jsp").forward(request, response);
				return;
			}
			String userName=request.getParameter("userName");
			UserDao dao = DaoFactory.getInstance(UserDao.class);
			try {
				User u = dao.findByUserName(userName);
				if(u!=null){
					request.setAttribute("userExisted", "用户名己存在，请更换");
					request.getRequestDispatcher("register.jsp").forward(request, response);
					return;
				}
				String name=request.getParameter("name");
				String passWord = request.getParameter("passWord");
				int age=Integer.parseInt(request.getParameter("age"));
				int gender=Integer.parseInt(request.getParameter("gender"));
				String phone=request.getParameter("phone");
				u = new User(userName, passWord, name, age, gender, phone);
				int id=dao.save(u);
				String path=getServletContext().getRealPath("photos");
				File userPhotosFolder=new File(path+"/photo_"+id);
				userPhotosFolder.mkdirs();
				request.getRequestDispatcher("login.jsp").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServletException(e);
			}
		}else if("/login".equals(action)){
			String userName=request.getParameter("userName");
			String passWord = request.getParameter("passWord");
			UserDao dao = DaoFactory.getInstance(UserDao.class);
			try {
				User u = dao.findByUserName(userName);
				if(u==null||!u.getPassWord().equals(passWord)){
					request.setAttribute("loginError", "用户不存在或密码错误");
					request.getRequestDispatcher("login.jsp").forward(request, response);
				}else{
					HttpSession session = request.getSession();
					session.setAttribute("id", u.getId());
					response.sendRedirect("userList.jsp");
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServletException(e);
			}
		}else if("/uploadPhoto".equals(action)){
			int id=Integer.parseInt(request.getParameter("id"));
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload sfu = new ServletFileUpload(factory);
			try {
				List<FileItem> fileItems = sfu.parseRequest(request);
				for(int i=0;i<fileItems.size();i++){
					FileItem item= fileItems.get(i);
					if(!item.isFormField()){
						String type = item.getContentType();
						if(type.toLowerCase().endsWith("jpeg")){
							String fileName=item.getName();
							fileName=fileName.substring(fileName.lastIndexOf("/")+1);
							Photo photo=new Photo();
							photo.setUserId(id);
							photo.setName(fileName);
							PhotoDao dao=DaoFactory.getInstance(PhotoDao.class);
							dao.save(photo);
							
							String userPhotosFolder=getServletContext().getRealPath("/photos/photo_"+id);
							File file = new File(userPhotosFolder+"/"+fileName);
							item.write(file);
						}
					}
				}
				response.sendRedirect("userDetail.jsp?id="+id);
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServletException(e);
			}
		}else if("/logout".equals(action)){
			HttpSession session=request.getSession();
			session.invalidate();
			response.sendRedirect("login.jsp");
		}
	}
}
